<?php
/**
 * RedCross Application
 *
 * @copyright Copyright (c) 2010, Kristian Stokke Tryggestad, Rune Vikestad, Andreas Flaten Wist, Simen Nicolai Echholt, Ole Henrik Jahren
 */


class RedCross_Form_Element_Time extends Zend_Form_Element_Xhtml
{

    private $_timeFormat = '%hours%:%minutes%:00';
    private $_hours;
    private $_minutes;

    public function init()
    {
        $this->addPrefixPath(
            'RedCross_Form_Decorator',
            'RedCross/Form/Decorator',
            'decorator'
        );

        $validator = new Zend_Validate_Regex('/^([0-1][0-9]|[2][0-3]):([0-5][0-9]):00$/');
        $validator->setMessage('Dette er ikke et gyldig klokkeslett', Zend_Validate_Regex::INVALID);
        $validator->setMessage('Dette er ikke et gyldig klokkeslett', Zend_Validate_Regex::NOT_MATCH);
        $this->addValidator($validator);
    }

    public function loadDefaultDecorators()
    {
        if ($this->loadDefaultDecoratorsIsDisabled()) {
            return;
        }

        $this->setDecorators(array(
            array('Time'),
            array('Errors'),
            array('Description'),
            array('Label'),
            array('HtmlTag', array('tag' => 'li'))
        ));
    }

    public function setHours($value)
    {
        $this->_hours = (int) $value;
        return $this;
    }

    public function setMinutes($value)
    {
        $this->_minutes = (int) $value;
        return $this;
    }

    public function getHours()
    {
        return $this->_hours < 10 ? '0' . $this->_hours : $this->_hours;
    }

    public function getMinutes()
    {
        return $this->_minutes < 10 ? '0' . $this->_minutes : $this->_minutes;
    }

    public function setValue($value)
    {
        if (is_array($value) && (isset($value['hours']) && isset($value['minutes']))) {
            $this->setHours($value['hours'])
                ->setMinutes($value['minutes']);
        } else if (is_string($value)) {
            $this->setHours(substr($value, 0, 2))
                ->setMinutes(substr($value, 3, 5));
        } else {
            throw new Exception('Invalid time value provided');
        }

        return $this;
    }

    public function getValue()
    {
        return str_replace(
            array('%hours%', '%minutes%'),
            array($this->getHours(), $this->getMinutes()),
            $this->_timeFormat
        );
    }

}
